// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const cmtCollection = db.collection('comment')
const closetimeCollection = db.collection('closetime')
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let closeTime
  let state

  await closetimeCollection.where({
    openid: wxContext.OPENID
  }).get().then(res => {
    // console.log(res.data.length)
    if (res.data.length == 0) 
      {
        state = false
      }else{
        closeTime = res.data[0].closetime
      }
  })

  await cmtCollection.where({
    authorId: wxContext.OPENID,
    commentatorId: _.neq(wxContext.OPENID),
    commentDate: _.gte(closeTime)
  }).count().then(res => {
    // console.log(closeTime)
    // console.log(res.total)
    if (res.total != 0){
      state = true
    }else{
      state = false
    }
  })
  if(!state){
    await cmtCollection.where({
      commentatorId: wxContext.OPENID,
      authorId: _.neq(wxContext.OPENID),
      reply: _.neq(''),
      replyDate: _.neq('').and(_.gte(closeTime))
    }).count().then(res => {
      // console.log(res.total)
      if (res.total != 0) {
        state = true
      } else {
        state = false
      }
    })
  }
  

  return state
}